package io.renren.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.security.MessageDigest;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

@Component("io.renren.util")
public class Util  implements ApplicationContextAware{
	private static final Logger logger = LoggerFactory.getLogger(Util.class);
	
	public static SimpleDateFormat formatDate = new SimpleDateFormat("yyyy-MM-dd");
	public static SimpleDateFormat formatDateTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	public static Date toDate(String str) {
		if(Util.IsNullOrEmpty(str)){
			return null;
		}
		try {
			if(str.length()>11) {
				Date date = formatDateTime.parse(str);
				return date;
			}else {
				Date date = formatDate.parse(str);
				return date;
			}
			
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return null;
	}
	/**
	 * yyyy-MM-dd
	 * @param str
	 * @param def
	 * @return
	 */
	public static Date toDate(String str,Date def){
		if(Util.IsNullOrEmpty(str)){
			return def;
		}
		try {
			if(str.length()>11) {
				Date date = formatDateTime.parse(str);
				return date;
			}else {
				Date date = formatDate.parse(str);
				return date;
			}
			
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return def;
	}
	
	public static Date toDate(String str,String format){
		if(Util.IsNullOrEmpty(str)){
			return null;
		}
		SimpleDateFormat formatDateTime = new SimpleDateFormat(format);
		Date date = null;
		try {
			date = formatDateTime.parse(str);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return date;
	}
	
	public static String toString(Calendar cal){
		return toString(cal.getTime());
	}
	
	public static String toString(Date date){
		if(null ==  date){
			return "";
		}
		return formatDateTime.format(date);
	}
	
	/**
	 * 
	 * @param date
	 * @param format
	 * @return
	 */
	public static String toString(Date date,String format){
		if(date==null){
			return null;
		}
		SimpleDateFormat f = new SimpleDateFormat(format);
		String str = "";
		str = f.format(date);
		return str;
	}
	
	public static int toInt(String str,int def){
		if(Util.IsNullOrEmpty(str)) {
			return def;
		}
		
		int ret = def;
		try {
			ret = Integer.valueOf(str);
		} catch (NumberFormatException e) {
			//e.printStackTrace();
		}
		
		return ret;
	}
	
	public static int toInt(String str) {
		return toInt(str,0);
	}
	
	public static Long toLong(String str){
		return toLong(str,0);
	}
	
	public static Long toLong(String str,long def){
		if(Util.IsNullOrEmpty(str)) {
			return def;
		}
		
		long ret = def;
		try {
			ret = Long.valueOf(str);
		} catch (NumberFormatException e) {
			//e.printStackTrace();
		}
		
		return ret;
	}
	
	public static BigDecimal toBigDecimal(String str){
		if(Util.IsNullOrEmpty(str)){
			return new BigDecimal(0);
		}
		
		try {
			BigDecimal b = new BigDecimal(str);
			return b;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
		}
		
		return new BigDecimal(0);
	}
	
	public static String toJson(Object obj){
		StringBuilder json= new StringBuilder();
		Class clazz = obj.getClass();
		Method[] methods = clazz.getDeclaredMethods();//返回当前类所有的(不含超类)
		logger.debug("len={}",methods.length);
		if(methods!=null){
			Method method = null;
			for(int i=0;i<methods.length;i++){
				method = methods[i];
				//logger.debug(method.getName());
				if(method.getName().startsWith("get") == false){
					continue;
				}
				String name=method.getName().substring(3);
				name = name.substring(0, 1).toLowerCase()+name.substring(1);
				
				json.append(",\"").append(name).append("\":");
				
				try {
					logger.debug("field={},{}",name,method.getReturnType());
					String val = null;
					Class type = method.getReturnType();
					if( type ==String.class){
						val = (String)method.invoke(obj);
						json.append("\"").append(val).append("\"");
					} else if(type == Date.class){
						val = Util.toString((Date)method.invoke(obj),"yyyy-MM-dd HH:mm:ss");
						json.append("\"").append(val).append("\"");
					} else {
						val = String.valueOf(method.invoke(obj));
						json.append(val);	
					}
					
					logger.debug("value={}",val);
					
				} catch (IllegalArgumentException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (InvocationTargetException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		
		return json.replace(0, 1, "{").append('}').toString();
	}
	
	
	public static String toGson(Object obj){
		Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
		return gson.toJson(obj);
	}
	
	public static <T> T toGson(String json){
		Type type = new TypeToken<T>(){}.getType();
		Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
		T t = gson.fromJson(json, type);
		return t;
	}
	
	public static boolean IsNullOrEmpty(String str){
		return null == str || "".equals(str.trim());
	}
	
	public static boolean IsNullOrEmpty(List<?> list){
		return null == list || list.size() <1;
	}
	
	public static boolean toBoolean(String str){
		boolean b = false ;
		if("true".equalsIgnoreCase(str) || "1".equalsIgnoreCase(str)){
			return b = true;
		}
		return b;
	}
	
	public static String IfNull(String str){
		if(str == null){
			return str = "";
		}
		return str;
	}
	
	public static String toJoin(String[] arr,String join){
		StringBuilder ret = new StringBuilder();
		
		for(String item : arr){
			ret.append(join).append(item);
		}
		
		return ret.substring(1).toString();
		
	}
	
	public static String MD5(String content) {
		byte[] source = content.getBytes();
		String s = null;
		char hexDigits[] = { // 用来将字节转换成 16 进制表示的字符
		'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',
				'e', 'f' };
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(source);
			byte tmp[] = md.digest(); // MD5 的计算结果是一个 128 位的长整数，
										// 用字节表示就是 16 个字节
			char str[] = new char[16 * 2]; // 每个字节用 16 进制表示的话，使用两个字符，
											// 所以表示成 16 进制需要 32 个字符
			int k = 0; // 表示转换结果中对应的字符位置
			for (int i = 0; i < 16; i++) { // 从第一个字节开始，对 MD5 的每一个字节
											// 转换成 16 进制字符的转换
				byte byte0 = tmp[i]; // 取第 i 个字节
				str[k++] = hexDigits[byte0 >>> 4 & 0xf]; // 取字节中高 4 位的数字转换,
															// >>>
															// 为逻辑右移，将符号位一起右移
				str[k++] = hexDigits[byte0 & 0xf]; // 取字节中低 4 位的数字转换
			}
			s = new String(str); // 换后的结果转换为字符串

		} catch (Exception e) {
			e.printStackTrace();
		}
		return s;
	}
	
	
	/**
	 * 删除文本内的网页标签
	 * @param html
	 * @return
	 */
     public static String htmlRemove(String html)
     {
         if(IsNullOrEmpty(html))
             return html;
         
         //删除脚本
         html = html.replaceAll("<script[^>]*?>.*?</script>", "");

         //删除图片
         html = html.replaceAll("<img[^>]*?>.*?</img>", "");

         //删除HTML空格
         html =html.replaceAll("&nbsp;"," ");
         
         //删除注释
         html = html.replaceAll("<!--[^>]*?-->", "");
         
         //删除HTML标签，保留标签之间的内容
         html = html.replaceAll("<(.[^>]*)>", "");

         html = html.replaceAll("([\r\n])[\\s]+", "");


         html = html.replaceAll( "\"","&(quot|#34);");

         html = html.replaceAll("&","&(amp|#38);");

         html = html.replaceAll("&#(\\d+);", "");


         html = html.replace("\r\n", "");
        

         return html;
     }
	
     /**
 	 * 删除文本内的网页标签
 	 * @param html
 	 * @param sublen 截取长度
 	 * @return
 	 */
      public static String htmlRemove(String html,int sublen)
      {
    	  String str = htmlRemove(html);
    	  int endIndex = str.length();
    	  endIndex = endIndex>sublen?sublen:endIndex;
    	  str = str.substring(0, endIndex);
    	  return str;
      }
      
      /**
       * 将html标签进行编码
       * @param val
       * @return
       */
     public static String htmEncode(String val){
     	//val = val.replace("&", "&amp");

         //val = val.replace(Chr(0),"");
     	//val = val.replace( char(13),"<br>");
     	
//         val = val.replace("'", "&apos;");
//         val = val.replace("\"", "&quot;");

         val = val.replace("<", "&lt;");
         val = val.replace(">", "&gt;");
//         val = val.replace("=", "&#061;");
         
//         val = val.replace("[", "&#091;");
//         val = val.replace("]", "&#093;");
//         
//         val =val.replaceAll("“","&ldquo;");
//         val =val.replaceAll("”","&rdquo;");
//         val =val.replaceAll("—","&mdash;");
         
         

         val = val.replaceAll("s((?i)cript)", "&#115;$1");
         val = val.replaceAll("S((?i)cript)", "&#083;$1");

         val = val.replaceAll("o((?i)bject)", "&#111;$1");
         val = val.replaceAll("O((?i)bject)", "&#079;$1");

         val = val.replaceAll("a((?i)pplet)", "&#097;$1");
         val = val.replaceAll("A((?i)pplet)", "&#065;$1");

         val = val.replaceAll("s((?i)elect)", "&#115;$1");
         val = val.replaceAll("S((?i)elect)", "&#083;$1");

     	return val;
     }
     
     /**
      * 将html标签解码
      * @param val
      * @return
      */
     public static String htmlDecode(String val){
     	
     	 //val = val.replace("&amp","&");
     	 
//     	 val = val.replace("&apos;","'");
//          val = val.replace("&quot;","\"");
//          val = val.replace("&#061;","=");
     	 val = val.replace("&lt;","<");
          val = val.replace("&gt;",">");
          
          
//          val = val.replace("&#091;","[");
//          val = val.replace("&#093;","]");
//          
//          val =val.replaceAll("&ldquo;","“");
//          val =val.replaceAll("&rdquo;","”");
//          val =val.replaceAll("&mdash;","—");
          
          return val;
     }
     
     
	 public static String sqlSafe(String val) {
		 	if(Util.IsNullOrEmpty(val)){
		 		return val;
		 	}
	        //TODO  过滤SQL有害字符串,参照上边replaceAll的写法,用正则表达式忽略大小写进行替换
	    	val = val.replace("'", "&apos;");
	        val = val.replace("\"", "&quot;");
	        val = val.replace("=", "&#061;");
	        val = val.replace("<", "&lt;");
	        val = val.replace(">", "&gt;");
	        val = val.replace("`", "&acute;");
	        /*
	        val = val.replace("execute", "&#101xecute");
	        val = val.replace("exec", "&#101xec");
	        val = val.replace("join", "jo&#105;n");
	        val = val.replace("union", "un&#105;on");
	        val = val.replace("where", "wh&#101;re");
	        val = val.replace("insert", "ins&#101;rt");
	        val = val.replace("delete", "del&#101;te");
	        val = val.replace("update", "up&#100;ate");
	        val = val.replace("like", "lik&#101;");
	        val = val.replace("drop", "dro&#112;");
	        val = val.replace("create", "cr&#101;ate");
	        val = val.replace("rename", "ren&#097;me");
	        val = val.replace("count", "co&#117;nt");
	        val = val.replace("chr", "c&#104;r");
	        val = val.replace("mid", "m&#105;d");
	        val = val.replace("truncate", "trunc&#097;te");
	        val = val.replace("nchar", "nch&#097;r");
	        val = val.replace("char", "ch&#097;r");
	        val = val.replace("alter", "alt&#101;r");
	        val = val.replace("cast", "ca&#115;t");
	        val = val.replace("exists", "e&#120;ists");
	        */
	        return val;
	    }
		

		public static String cleanXSS(String value) {
			if(Util.IsNullOrEmpty(value)){
				return value;
			}
			//You'll need to remove the spaces from the html entities below
	        //value = value.replaceAll("<script([^>]*)>(.*)</script>", "&lt;script$1$gt;$2&lt;/script$1$gt;");
	        value = value.replaceAll("<script([^>]*)>(.*)</script>", "");
	        value = value.replaceAll("<script[^>]*?>.*?</script>", "");
	        value = value.replaceAll("\\(", "& #40;").replaceAll("\\)", "& #41;");
	        value = value.replaceAll("'", "& #39;");
	        value = value.replaceAll("eval\\((.*)\\)", "");
	        value = value.replaceAll("[\\\"\\\'][\\s]*javascript:(.*)[\\\"\\\']", "\"\"");
	        return value;
	    }

		

		

   
     
     /**
 	 * 解压文件内的文件夹到指定目录
 	 * @param filePath 压缩包路径
 	 * @param dir 要解压的文件夹
 	 * @param savepath 保存路径
 	 */
 	public static void unZip(String filePath, String dir, String savepath,boolean overwrite) {
 		File f1 = new File(filePath);
 		if(f1.exists()== false || f1.isFile() == false){
 			return;
 		}
 		
 		int count = -1;
 		final int buffer = 2048;

 		try {
 			BufferedOutputStream bos = null;
 			ZipEntry entry = null;
 			FileInputStream fis = new FileInputStream(filePath);
 			ZipInputStream zis = new ZipInputStream(
 					new BufferedInputStream(fis));

 			while ((entry = zis.getNextEntry()) != null) {
 				byte data[] = new byte[buffer];

 				String temp = entry.getName();

 				if (temp.startsWith(dir) == false) {
 					continue;
 				}

 				temp = savepath + temp.replace('/', File.separatorChar);
 				File f = new File(temp);
 				if(temp.endsWith(File.separator)){
 					f.mkdirs();
 					continue;
 				}
 				
 				if(f.exists() && overwrite == false){
 					continue;
 				}
 				
 				logger.debug("解压文件:\t"+temp);
 				
 				f.createNewFile();

 				FileOutputStream fos = new FileOutputStream(f);
 				bos = new BufferedOutputStream(fos, buffer);

 				while ((count = zis.read(data, 0, buffer)) != -1) {
 					bos.write(data, 0, count);
 				}

 				bos.flush();
 				bos.close();

 			}

 			zis.close();

 		} catch (Exception e) {
 			e.printStackTrace();
 		}
 	}
 	
 	/**
 	 * 数据库行转实体
 	 * @param t
 	 * @param rs
 	 * @param rowNum
 	 * @throws SQLException
 	 */
 	public static <T> void rowMapper(T t,ResultSet rs, int rowNum) throws SQLException{
 		Util.rowMapper("",t,rs,rowNum);
 	}
 	/**
 	 * 数据库行转实体
 	 * @param pre 前缀
 	 * @param t
 	 * @param rs
 	 * @param rowNum
 	 * @throws SQLException
 	 */
 	public static <T> void rowMapper(String pre,T t,ResultSet rs, int rowNum) throws SQLException{
 		ResultSetMetaData mdata = rs.getMetaData();
		for(int i=1;i<=mdata.getColumnCount();i++){
			String colname = pre + mdata.getColumnLabel(i);
			Method[] mlist =t.getClass().getMethods();
			for(Method m : mlist){
				if(m.getName().startsWith("set") && m.getName().substring(3).equalsIgnoreCase(colname)){
					
					try {
						//TODO 使用switch 优化
						 Class<?>[] clazz = m.getParameterTypes();  
			             String type = clazz[0].getName();  
			            //logger.debug("rowmapper:col={},type={}",colname,type);
						if(type.equals("java.lang.String")){  
		                    m.invoke(t,rs.getString(colname));  
		                } else if(type.equals("java.util.Date") || type.equals("java.sql.Date")){  
		                    m.invoke(t, rs.getTimestamp(colname));  
		                } else if(type.equals("java.sql.Timestamp")){  
		                    m.invoke(t, rs.getTimestamp(colname));  
		                } else if(type.equals("java.lang.Short") || type.equals("short")){
		                	m.invoke(t, rs.getShort(colname));
		                } else if(type.equals("java.lang.Long") || type.equals("long")){  
		                    m.invoke(t, rs.getLong(colname));  
		                } else if(type.equals("java.lang.Integer") || type.equals("int")){  
		                    m.invoke(t, rs.getInt(colname));  
		                } else if(type.equals("java.lang.Float") || type.equals("float")){
		                    m.invoke(t, rs.getFloat(colname));  
		                } else if(type.equals("java.lang.Double") || type.equals("double")){  
		                    m.invoke(t, rs.getDouble(colname));  
		                } else if(type.equals("java.math.BigDecimal")){  
		                    m.invoke(t, rs.getBigDecimal(colname));  
		                } else if(type.equals("java.lang.Boolean") || type.equals("boolean")){  
		                    m.invoke(t, rs.getBoolean(colname));  
		                } else{  
		                	//m.invoke(t,rs.getObject(colname));  
		                	logger.warn("rowmapper:col={},type={}",colname,type);
		                }  
						
					} catch (IllegalAccessException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IllegalArgumentException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (InvocationTargetException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
			
		}
		
 	}
 	
 	/**
 	 * 表单转实体
 	 * @param t
 	 * @param request
 	 */
 	public static <T> void formMapper(String pre,T t,HttpServletRequest request){
 		if(null == pre){
 			pre = "";
 		}
 		Method[] methods = t.getClass().getMethods();
 		
 		for(Method m : methods) {
 			
 			if(m.getName().startsWith("set")){
 				String key =  m.getName().substring(3);
 				key = pre + key.substring(0, 1).toLowerCase()+key.substring(1);
 				String val = request.getParameter(key);
 				
				try {
					//TODO 使用switch 优化
					 Class<?>[] clazz = m.getParameterTypes();  
		             String type = clazz[0].getName();  
		             logger.debug("type:{},key:{},val:{}",type,key,val);
		             if(null != val){
						if(type.equals("java.lang.String")){  
		                    m.invoke(t,val);  
		                } else if(type.equals("java.util.Date") || type.equals("java.sql.Date")){  
		                    m.invoke(t, Util.toDate(val));  
		                } else if(type.equals("java.lang.Short") || type.equals("short")){
		                	m.invoke(t, Short.valueOf(val));
		                } else if(type.equals("java.lang.Long") || type.equals("long")){  
		                    m.invoke(t, Long.valueOf(val));  
		                } else if(type.equals("java.lang.Integer") || type.equals("int")){  
		                    m.invoke(t, Integer.valueOf(val));  
		                } else if(type.equals("java.lang.Float") || type.equals("float")){
		                    m.invoke(t,Float.valueOf(val));  
		                } else if(type.equals("java.lang.Double") || type.equals("double")){  
		                    m.invoke(t, Double.valueOf(val));  
		                } else if(type.equals("java.math.BigDecimal")){  
		                    m.invoke(t, BigDecimal.valueOf(Double.valueOf(val)));  
		                } else if(type.equals("java.lang.Boolean") || type.equals("boolean")){  
		                    m.invoke(t, Boolean.valueOf(val));  
		                } else{  
		                	logger.warn("rowmapper:col={},type={}",key,type);
		                }  
		             } 
				} catch (IllegalAccessException e) {
					// TODO Auto-generated catch block
					//e.printStackTrace();
					logger.warn(e.getMessage());
				} catch (IllegalArgumentException e) {
					// TODO Auto-generated catch block
					//e.printStackTrace();
					logger.warn(e.getMessage());
				} catch (InvocationTargetException e) {
					// TODO Auto-generated catch block
					//e.printStackTrace();
					logger.warn(e.getMessage());
				}
 				
 			}
 		}
 	}
 	
 	/**
	* 产生随机字串，可用来自动生成密码
	* 默认长度6位 字母和数字混合 支持中文
	* @param  len 长度 最少6位
	* @param  type 字串类型 0＝数字， 1＝大小写英文，2＝大写英文，3＝小写英文,4=大小写英文数字
	* @param  addChars 额外字符
	* @return 
	*/
	
	public static String rand(int len , int type, String addChars) {
		//最少6位
		len = len <6?6:len;
		addChars = addChars ==null?"":addChars;
		StringBuffer result = new StringBuffer();
		String s = "0123456789";
		String s0 = "abcdefghijklmnopqrstuvwxyz";
		String s1 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
		StringBuffer sb = new StringBuffer();
		switch (type) {
			case 0 :
				sb.append(s).append(s).append(s);
				break;
			case 1 :
				sb.append(s1).append(s0).append(addChars);
				break;
			case 2 :
				sb.append(s1).append(addChars);
				break;
			case 3 :
				sb.append(s0).append(addChars);
				break;
			default :
				sb.append(s1).append(s0).append(s).append(addChars);
				break;
		}
		
		
		if (len > 10) { //位数过长,重复字符串一定次数
			int k = type==1?len:5;
			for (int i = 0; i < k; i++) {
				sb.append(sb.toString());
			}
		} 
		
		for (int i = 0; i < len; i++) {
			int start = (int) Math.ceil(Math.floor(Math.random()*(sb.length()-1) *10) /10 );
			int end = start+1;
			result.append(sb.substring(start,end));
		}
		
		return result.toString();
	}
	
	
	//Spring应用上下文环境
	private static ApplicationContext applicationContext;
	
	/**
	 * 实现ApplicationContextAware接口的回调方法，设置上下文环境
	 */
	public void setApplicationContext(ApplicationContext context)
	        throws BeansException {
	    applicationContext = context;
	}
	
	public static ApplicationContext getApplicationContext() {
	    return applicationContext;
	}
	
	/**
	 * 获取对象 这里重写了bean方法，起主要作用
	 */
	public static Object getBean(String beanId) throws BeansException {
	    return applicationContext.getBean(beanId);
	}
	
	public static <T> T getBean(Class<T> clazz){
		try {
			return applicationContext.getBean(clazz);
		} catch (BeansException e) {
			//e.printStackTrace();
		}
		
		return null;
	}
	
	public static synchronized String upload(HttpServletRequest request,String fieldName,String allows, int maxSize){
		StringBuilder msg= new StringBuilder();
		String savePath = "/upload/files/" + Calendar.getInstance().get(Calendar.YEAR) + "/";
		String saveName = "" + System.currentTimeMillis();
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		MultipartFile file = multipartRequest.getFile(fieldName);
		
		if(file.isEmpty()==false ){
			//文件名
			String fileName = file.getOriginalFilename().substring(0,file.getOriginalFilename().lastIndexOf("."));
			
			//扩展名
			String extensionName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")+1);
			
			if(Util.IsNullOrEmpty(allows) == false && allows.toLowerCase().contains(extensionName.toLowerCase()) == false){
				msg.append("标题图片不符合要求:").append(allows);
			}
			
			long size = file.getSize();
			if(size>maxSize){
				msg.append("标题图片不能大于").append(Math.floor(maxSize/1024/1024)).append("MB");
			}
			
	        //如果用的是Tomcat服务器，则文件会上传到\\%TOMCAT_HOME%\\webapps\\YourWebProject\\savePath\\文件夹中  
	        String realPath = request.getSession().getServletContext().getRealPath(savePath);
	        File targetFile = new File(realPath, saveName +"."+extensionName);
			if (!targetFile.exists()) {
				targetFile.mkdirs();
			}
			// 保存
			try {
				file.transferTo(targetFile);
			} catch (IllegalStateException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
	    }
		if(msg.length()>0){
			msg.insert(0, "error");
		}
		return msg.toString();
		
	}
	
	
	public static String mysql(JdbcTemplate jdbcTemplate,File file){
		//逐条执行sql
		List<String> list = new ArrayList<String>();
        try {
            String encoding="UTF-8";
            if(file.isFile() && file.exists()){ //判断文件是否存在
                InputStreamReader read = new InputStreamReader(
                new FileInputStream(file),encoding);//考虑到编码格式
                BufferedReader bufferedReader = new BufferedReader(read);
                String lineTxt = null;
                String ret = "";
                while((lineTxt = bufferedReader.readLine()) != null){
                    ret += lineTxt;
                    if(lineTxt.contains(";")){
                    	list.add(ret);
                    	ret = "";
                    }
                }
                read.close();
	        } else {
	            System.out.println("找不到指定的文件");
	        }
        } catch (Exception e) {
            System.out.println("读取文件内容出错");
            e.printStackTrace();
        }
		String ret = "";
		for(String sql :list){
			try {
				int count = jdbcTemplate.update(sql);
			} catch (DataAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			ret += sql +"<br />";
		}
		return ret;
	}
}
